import router from './router'
import store from './store'

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  // console.log('to', to)
  // console.log(store.state.user)
  if (store.state.user) {
    if (to.meta.navbarTitle !== undefined) {
      store.state.navbarTitle = to.meta.navbarTitle
      // console.log('navbarTitle', store.state.navbarTitle)
    }
    if (to.path === '/login') {
      next('/')
    } else {
      const userRole = store.state.user.role
      // console.log('userRole', userRole)
      // console.log('to', to)
      if (to.meta.roles === undefined) {
        // console.log('1')
        next()
      } else {
        // console.log('2')
        if (to.meta.roles.indexOf(userRole) !== -1) {
          next()
        } else {
          next('/404')
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
